// 首页地图功能
// 获取当前地理位置
const QQMapWX = require('../utils/libs/qqmap-wx-jssdk')
var qqmapsdk;
qqmapsdk = new QQMapWX({
  key: '4RKBZ-J7ECO-VO6WS-SN5VJ-XTOEK-USBVI'
});
function getLocation(pageThis, callBack) {
  var _this = pageThis
  let mapCurrent = wx.getStorageSync('location')
  if(mapCurrent && !mapCurrent.isFirstGet ) {
    return
  }
  wx.getLocation({
    type: 'gcj02',
    success(res) {
      // 调用sdk接口
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: res.latitude,
          longitude: res.longitude
        },
        success: function (res) {
          let o = res.result
          let object = {
            lat: o.location.lat,
            lng: o.location.lng,
            address: o.address,
            city: o.address_component.city
          }
          callBack(res)
        },
        fail:function(res){
          console.log(res)
        }
      })
    },
    fail(res) {
      // 引导授权
      wx.getSetting({
        success: (res) => {
          let status = res.authSetting
          if(!status['scope.userLocation']) {
            wx.showModal({
              title: '是否授权当前位置',
              content:'需要获取您的地理位置，请确认授权，否则滴入功能将无法使用',
              showCancel:false,
              success:function(tip) {
                if(tip.confirm) {
                  // 确认授权
                  wx.openSetting({
                    success: (data) => {
                      if(data.authSetting['scope.userLocation'] === true) {
                        wx.showToast({
                          title: '授权成功',
                          icon:'none',
                          duration:1000
                        })
                        getLocation(pageThis,callBack)
                      }
                      
                    },
                  })
                }
              }
            })
          }
          
        },
      })
    }
  })
}
// 移动选址中心点
function getCenterLocation(mapName, pageThis, callBack) {
  let mapCtx = wx.createMapContext(mapName, pageThis);
  mapCtx.getCenterLocation({
    type: 'gcj02',
    success: function (res) {
      callBack(res)
    }
  })

}
// 获取周边地点列表
function getPoiList(longitude, latitude, getDetailData) {
  qqmapsdk.reverseGeocoder({
    location: {
      latitude: latitude,
      longitude: longitude,
    },
    // get_poi: 1,
    // poi_options: 'policy=5;radius=10;page_size=10;page_index=1',
    success: function (res) {
      /**详细数据从这儿拿*/
      getDetailData(res)
    },
    fail: function (res) {
    },
    complete: function (res) {

    }
  });
}
// 获取距离
function distanceCount(start, end) {
  var _this = this;
  return new Promise((resolve, reject) => {
    //调用距离计算接口
    qqmapsdk.direction({
      mode: 'bicycling',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
      //from参数不填默认当前地址
      //获取表单提交的经纬度并设置from和to参数（示例为string格式）
      from: start || '', //若起点有数据则采用起点坐标，若为空默认当前地址
      to: end, //终点坐标
      speed:40,
      success: function (res) {//成功后的回调
        resolve(res)
      },
      fail: function (error) {
        reject(res)
      },
    });
  })

}

function wxPromise(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }
      obj.fail = function (res) {
        reject(res)
      }
      fn(obj)
    })
  }
}

module.exports = {
  getLocation: getLocation, // 获取当前地理位置
  getCenterLocation: getCenterLocation, // 获取中心点位置
  getPoiList: getPoiList,  // 距离划线
  distanceCount: distanceCount, //地图距离计算
  wxPromise: wxPromise

}